#!/bin/bash

ifeq (,$(TOP_DIR))
#TOP_DIR := $(shell pwd)/..
TOP_DIR := $(shell pwd)/..
CURRENT_DIR := $(shell pwd)
else
CURRENT_DIR := $(TOP_DIR)/tests
endif

#########################COM LIB#################################
COM_LIBS += -lssl -lcrypto
COM_LIBS += -lglib-2.0

######################### GTests #################################
GTEST_KMS_SRC = $(CURRENT_DIR)/gtest_kms.c
GTEST_CMS_SRC = $(CURRENT_DIR)/gtest_cms.c

GTEST_KMS_OBJ = $(GTEST_KMS_SRC:.c=.o)
GTEST_CMS_OBJ = $(GTEST_CMS_SRC:.c=.o)

######################### COM INCLUDE #################################
COM_INCLUDE_PATH := -I $(CURRENT_DIR)/../include/
COM_INCLUDE_PATH += -I /usr/include/
COM_INCLUDE_PATH += -I /usr/include/glib-2.0/
COM_INCLUDE_PATH += -I /usr/lib/x86_64-linux-gnu/glib-2.0/include
COM_INCLUDE_PATH += -I /usr/lib64/glib-2.0/include


GTEST_TARGET_CMS = $(CURRENT_DIR)/gtest_cms
GTEST_TARGET_KMS = $(CURRENT_DIR)/gtest_kms

###########################QTSM_SAM###############################
QTSM_SDK_SRC := $(shell find $(CURRENT_DIR)/../source -name '*.c')
QTSM_SAM_SRC = $(shell find $(CURRENT_DIR) -name 'qtsm-sdk-test.c')
QTSM_SDK_OBJ = $(QTSM_SDK_SRC:.c=.o)
QTSM_SAM_OBJ = $(QTSM_SAM_SRC:.c=.o)

QTSM_SAM_TARGET = $(CURRENT_DIR)/qtsm_sdk_test

QTSM_LIB_PATH += -L $(TOP_DIR)/../qtsm/lib
QTSM_LIB_PATH += -L /usr/bin

QTSM_SDK_LIB_PATH += -lcurl
QTSM_SDK_LIB_PATH += -ljson-c
QTSM_SDK_LIB_PATH += -lqtsm
QTSM_SDK_LIB_PATH += -lpthread

QTSM_INCLUDE_PATH := -I $(TOP_DIR)/../qtsm/include
QTSM_INCLUDE_PATH += -I /usr/local/include/cjson

ifeq (,$(CC))
CC := gcc
endif

GCC_CHOOSE := -W -Os -g
GCC_CHOOSE += -Wl,-z,relro,-z,now
GCC_CHOOSE += -Wl,-z,noexecstack
GCC_CHOOSE += -fstack-protector-strong

all: qtsm_sdk_test gtest_kms gtest_cms

$(QTSM_SDK_OBJ): %.o: %.c
	$(CC) -c $(GCC_CHOOSE) $< -o $@ $(COM_INCLUDE_PATH) $(QTSM_INCLUDE_PATH)

$(QTSM_SAM_OBJ): %.o: %.c
	$(CC) -c $(GCC_CHOOSE) $< -o $@ $(COM_INCLUDE_PATH) $(QTSM_INCLUDE_PATH)

$(GTEST_KMS_OBJ): %.o: %.c
	$(CC) -c $(GCC_CHOOSE) $< -o $@ $(COM_INCLUDE_PATH)

$(GTEST_CMS_OBJ): %.o: %.c
	$(CC) -c $(GCC_CHOOSE) $< -o $@ $(COM_INCLUDE_PATH)

qtsm_sdk_test:$(QTSM_SAM_OBJ) $(QTSM_SDK_OBJ)
	$(CC) $(GCC_CHOOSE) -o $@ $(QTSM_SDK_OBJ) $(QTSM_SAM_OBJ) $(QTSM_LIB_PATH) $(COM_LIBS) $(QTSM_SDK_LIB_PATH)

gtest_kms:$(GTEST_KMS_OBJ) $(QTSM_SDK_OBJ)
	$(CC) $(GCC_CHOOSE) -o $@ $(GTEST_KMS_OBJ) $(QTSM_SDK_OBJ) $(QTSM_LIB_PATH) $(COM_LIBS) $(QTSM_SDK_LIB_PATH)

gtest_cms:$(GTEST_CMS_OBJ) $(QTSM_SDK_OBJ)
	$(CC) $(GCC_CHOOSE) -o $@ $(GTEST_CMS_OBJ) $(QTSM_SDK_OBJ) $(QTSM_LIB_PATH) $(COM_LIBS) $(QTSM_SDK_LIB_PATH)

clean:
	rm $(QTSM_SAM_TARGET) $(GTEST_TARGET_CMS) $(GTEST_TARGET_KMS) \
	   $(QTSM_SDK_OBJ) $(GTEST_KMS_OBJ) $(GTEST_CMS_OBJ) $(QTSM_SAM_OBJ) \
	   -rf
